package com.jt.filter;

import org.apache.http.HttpHeaders;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.*;
@ConfigurationProperties("web.request")
@Component
public class BlackUrlGlobalFilter implements GlobalFilter, Ordered {
    private List<String> blackUrls = new ArrayList<>();

//    public BlackUrlGlobalFilter() {
//        blackUrls.add("/nacos/provider/echo/9002");
//        blackUrls.add("/nacos/provider/echo/9003");
//    }

    public void setBlackUrls(List<String> blackUrls){
        this.blackUrls = blackUrls;
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径(不需要ip和端口)
        String requestPath = request.getURI().getPath();
        //判定请求路径是否是黑名单,假如是则给出反馈
        if(blackUrls.contains(requestPath)){
            //throw  new RuntimeException("这个请求已被列入黑名单");
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE,"text/html;charset=utf-8");
            DataBuffer data = response.bufferFactory().wrap("当前url不允许访问资源".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(data));

        }
        //不是黑名单继续执行下一步操作
        return chain.filter(exchange);
    }
//定义过滤器的优先级,数字越小,优先级越高
    @Override
    public int getOrder() {
        return -1;
    }
}
